const express=require('express');
const util=require('../libs/util');
const config =require('../config')
const fs=require('fs')
let router=express.Router();

module.exports=router;

//进入admin相关的页面前，先验证是否登录，没有跳转到登录页面
router.use((req,res,next)=>{
    if(!req.cookies['admin_token']&&req.path!="/login"){
        res.redirect(`/admin/login?ref=${req.url}`);
    }else{
        if(req.path=='/login'){
            next();
        }else{
            req.db.query(`select * from admin_token_table where ID='${req.cookies['admin_token']}'`,(err,data)=>{
                if(err){
                    console.log(err);
                    res.sendStatus(500)
                }else if(data.length==0){
                    console.log("toke 不是合法值");
                    res.redirect(`/admin/login?ref=${req.url}`);      
                }else{
                    req.admin_ID=data[0]['admin_ID'];
                    next();
                }
            })
        }
    }
});
//展示login页面
router.get('/login',(req,res)=>{
    res.render('login',{error_msg:'',ref: req.query['ref']||''});
});
//提交登录请求页面
router.post('/login',(req,res,next)=>{
    let {username,password}=req.body;

    function setToken(id){
        let ID=util.uuid();
        let oDate=new Date();
        //二十分钟过期
        oDate.setMinutes(oDate.getMinutes()+20);
        let t=Math.floor(oDate.getTime()/1000);

        req.db.query(`insert into admin_token_table (ID, admin_ID, expires) values ('${ID}','${id}','${t}')`,err=>{
            if(err){
                console.log(err);
                res.sendStatus(500)
            }else{
                res.cookie('admin_token',ID);
                let ref=req.query['ref'];
                if(!ref){
                    ref=''
                }
                res.redirect('/admin'+ref);
            }
        })
    }


    if(username==config.root_username){
        if(util.md5(password)==config.root_password){
            //req.session['admin_ID']='1';
            //res.redirect('/admin/');
            setToken(1);
        }else{
            showError('用户名或密码错误！');
        }
    }else{
        req.db.query(`select * from admin_table where username='{username}'`,(err,data)=>{
            if(err){
                showError('数据库查询错误！');
            }else if(data.length==0){
                showError('用户名或密码错误！');
            }else{
              if(data[0].password==util.md5(password)){
                // req.session['admin_ID']=data[0].ID;
                // res.redirect('/admin/')
                setToken(data[0].ID)
              }else{
                showError('用户名或密码错误！');
              }
            }
        });
    }
    function showError(msg){
        res.render('login',{error_msg:msg,ref: req.query['ref']||''});
    }
});

router.get('/',(req,res)=>{
    res.redirect('/admin/house');
});
//查询所有的房子
router.get('/:table',(req,res)=>{
    
    const {table}=req.params;
    //判断查询的数据是否在配置文件中
    if(!config[`show_in_admin_${table}`]){
        res.sendStatus(404);
    }else{
        //要查询的 字段
        let afiled=[];
        //要在前台页面展示的字段名称
        let jsonShowName={};

        config[`show_in_admin_${table}`].split(',').forEach(item=>{
            let [filed, showname]=item.split(':');
            afiled.push(filed);
            jsonShowName[filed]=showname;
        });
        //分页
        const size=10;
        let page=req.query.page
        if(!page){
            page=1;
        }else if(!/^[1-9]\d*$/.test(page)){
            page=1;
        }
        let start = (page-1)*size;
        //搜索
        let like_seg='1=1';
        if(req.query.keyword){
            let keys=req.query.keyword.split(/\s+/g);
            like_seg=keys.map(item=>`title LIKE '%${item}%'`).join(' OR ');
          }
        //1.获取数据  
        req.db.query(`SELECT ${afiled.join(',')} FROM ${table}_table WHERE ${like_seg} LIMIT ${start}, ${size}`, (err, result) => {
            if (err) {
                res.sendStatus(500);
            } else {
                //2.获取总数据量
                req.db.query(`SELECT COUNT(*) AS c FROM ${table}_table WHERE ${like_seg}`, (err, data) => {
                    if (err) {
                        res.sendStatus(500);
                    } else if (data.length == 0) {
                        res.sendStatus(500);
                    } else {
                       // console.log(result,jsonShowName)
                        res.render('index', {
                            data: result,
                            show_page_count: 9,
                            cur_page: parseInt(page),
                            page_count: Math.ceil(data[0].c / size),
                            keyword: req.query.keyword,
                            jsonShowName,
                            table
                        });
                    }
                });
            }
        });

    }

   
    // req.db.query(`select ID, title,ave_price, tel from house_table` ,(err,data)=>{
    //     if(err){
    //         res.sendStatus(500);
    //     }else{
    //         res.render('index',{data});
    //     }
    // })
});
//提交房子/修改房屋
router.post('/:table',(req,res)=>{
    const {table}=req.params;

    //将表单提交的时间改为数据库能存储的时间
    // req.body['sale_time']=Math.floor(new Date(req.body['sale_time']).getTime()/1000);
    // req.body['submit_time']=Math.floor(new Date(req.body['submit_time']).getTime()/1000);
    if(req.body['is_mod']=='true'){
        if(!config[`insert_fields_${table}`]){
            res.sendStatus(404);
        }else{
            //筛选出去可以修改的字段
           let fileds= config[`insert_fields_${table}`].split(',');
           config['disallow_modify_fields'].split(',').forEach(name=>{
                fileds=fields.filter(item=>item!=name)
           });
           //可以修改字段的值
           let arr=[];
           fields.forEach(key=>{
           arr.push(`${key}='${req.body[key]}'`);
           });
           let sql=`UPDATE ${table}_table SET ${arr.join(',')} WHERE ID='${req.body['old_id']}'`;

            req.db.query(sql, err=>{
            if(err){
                res.sendStatus(500);
            }else{
                res.redirect(`/admin/${table}`);
            }
            });
        }
    }else{
        const file_infos={
            house: {
              'main_img': {
                path: 'main_img_path',
                real_path: 'main_img_real_path',
                type: 'single'
              },
              'img': {
                path: 'img_paths',
                real_path: 'img_real_paths',
                type: 'array'
              },
              'property_img': {
                path: 'property_img_paths',
                real_path: 'property_img_real_paths',
                type: 'array'
              },
            },
            'broker': {
              'img': {
                path: 'img_path',
                real_path: 'img_real_path',
                type: 'single'
              }
            },
            'ad': {
              'img': {
                path: 'img_path',
                real_path: 'img_real_path',
                type: 'single'
              }
            },
          };
        let file_info=file_infos[table];

        const file_paths={};
        const file_real_paths={};
        for(let i=0;i<req.files.length;i++){
            let name=req.files[i].fieldname;
            if(file_info[name]){
                if(!file_paths[name]){
                    file_paths[name]=[];
                    file_real_paths[name]=[];
                }
                file_paths[name].push(req.files[i].filename);
                file_real_paths[name].push(req.files[i].path.replace(/\\/g,'\\\\'));
            }
        }

        for(let name in file_paths){
            if(file_info[name].type=='single'){
                req.body[file_info[name].path]=file_paths[name][0];
                req.body[file_info[name].real_path]=file_real_paths[name][0];
            }else{
                req.body[file_info[name].path]=file_paths[name].join(',');
                req.body[file_info[name].real_path]=file_real_paths[name].join(',');
            }
        }


       


        req.body['ID']=util.uuid();
        req.body['admin_ID'] =req.admin_ID
        let arrFiled=[];
        let arrValue=[];

        config[`insert_fields_${table}`].split(',').forEach(item=>{
            arrFiled.push(item);
            arrValue.push(req.body[item]);
        })
        arrFiled.push('create_time');
        arrValue.push(Math.floor(new Date().getTime()/1000));


      
        let sql=`insert into ${table}_table (${arrFiled.join(',')}) values ('${arrValue.join("','")}')`
        console.log(sql);
        req.db.query(sql,(err)=>{
            if(err){
                console.log("添加失败");
                res.sendStatus(500);
            }else{
                res.redirect(`/admin/${table}`)
            }
        })
    }
});
//删除房屋
router.get("/:table/delete",(req,res)=>{

    const {table}=req.params;
    
    //判断查询的数据是否在配置文件中
    if(!config[`show_in_admin_${table}`]){
        res.sendStatus(404);
    }
    console.log("sssss")
   let ID=req.query['id'];

   let aID=ID.split(',');
   let b_err=false;
   aID.forEach(item=>{
       if(!/^(\d|[a-f]){32}$/.test(item)){
           b_err=true;
       }
   });
   if(b_err){
       res.sendStatus(400);
   }else{

       let j=0;
       delOne(aID[j++]);
       function delOne(ID){
        req.db.query(`select * from ${table}_table where ID='${ID}'`,(err,data)=>{
            if(err){
                res.sendStatus(500)
            }else if(data.length==0){
                res.sendStatus(404,'no data'); 
            }else{
                const file_infos={
                    house: {
                      'main_img': {
                        path: 'main_img_path',
                        real_path: 'main_img_real_path',
                        type: 'single'
                      },
                      'img': {
                        path: 'img_paths',
                        real_path: 'img_real_paths',
                        type: 'array'
                      },
                      'property_img': {
                        path: 'property_img_paths',
                        real_path: 'property_img_real_paths',
                        type: 'array'
                      },
                    },
                    'broker': {
                      'img': {
                        path: 'img_path',
                        real_path: 'img_real_path',
                        type: 'single'
                      }
                    },
                    'ad': {
                      'img': {
                        path: 'img_path',
                        real_path: 'img_real_path',
                        type: 'single'
                      }
                    },
                  };
                  let arr=[];
                //
                let file_info=file_infos[table];
                for (let item in file_info){
                    console.log(file_info[item].real_path);
                    if(data[0][`${file_info[item].real_path}`]){
                        if(file_info[item]['type']=='single'){
                            arr.push(data[0][`${file_info[item]['real_path']}`])
                        }else{
                            data[0][`${file_info[item]['real_path']}`].split(',').forEach(element => {
                                          arr.push(element);
                                      });
                        }
                    }
                }
                
                // data[0]['main_img_real_path']&&arr.push(data[0]['main_img_real_path']);
                // if(data[0]['img_real_paths']){
                //      data[0]['img_real_paths'].split(',').forEach(element => {
                //          arr.push(element);
                //      });
                // }
                // if( data[0]['property_img_real_paths']){
                //  data[0]['property_img_real_paths'].split(',').forEach(item=>{
                //      arr.push(item);
                //  });
                // }
                let i=0;
               if(arr.length>0){
                 
                 deleteImg();
               }else{
                 deleteFromDB();
               }
               //删除数据库记录之前，先删除磁盘图片
               function deleteImg(){
                   fs.unlink(arr[i],err=>{
                       if(err){
                           res.sendStatus(500);
                           console.log(err);
                       }else{
                           i++;
                           if(i>=arr.length){
                             deleteFromDB();
                           }else{
                             deleteImg(); 
                           }
                       }
                   })
               }
               
               function deleteFromDB(){
                 req.db.query(`delete from ${table}_table where ID ='${ID}'`,err=>{
                     if(err){
                         res.sendStatus(500);
                         console.log(err);
                     }else{
                        if(j>=aID.length){
                            res.redirect(`/admin/${table}`)
                        }else{
                            delOne(aID[j++])
                        }
                     }
                   })
               }
            }
        })
       }
   }

 

    
})

//获取房屋信息
router.get('/:table/get_data', (req, res)=>{
    const {table}=req.params;

    let id=req.query.id;
    if(!id){
      res.sendStatus(404);
    }else if(!/^[\da-f]{32}$/.test(id)){
      res.sendStatus(400);
    }else{
      req.db.query(`SELECT * FROM ${table}_table WHERE ID='${id}'`, (err, data)=>{
        if(err){
          res.sendStatus(500);
        }else if(data.length==0){
          res.sendStatus(404);
        }else{
          res.send(data[0]);
        }
      });
    }
  });
